(function() {
/*** ------------------------------javascript 原生对象扩展----------------------------*/
/** *************************** String扩展 ************************* */
encode = function(str) {
	if (str && typeof str == 'string')
		return str.encode();

	return str;
}

/**
 * @description 避免出现跨站脚本漏洞，将需要显示在页面上的数据的进行转义
 * @returns {string}
 */
String.prototype.encode = function(isProperty) {
	return this.replace(/</g, "&lt;").replace(/>/g, '&gt;').replace(/"/g, isProperty ? '\"' :  '&quot;' );
}
/**
 * @description 避免出现跨站脚本漏洞，将html中的script脚本、元素中以on开始的事件以及a标签中的href里面的事件处理掉。
 */
String.prototype.encodeHtml = function(){
	var html = this.replace(Ccay.Config.HtmlRegular.script,"");
	html = html.replace(Ccay.Config.HtmlRegular.elementEvent,"");
	html = html.replace(Ccay.Config.HtmlRegular.hrefEvent,"");
	return html;
};
/**
 * @description 得到字符串长度（中文算两个长度，数字字母算一个）
 * @return {number} sum 字符串长度
 */
String.prototype.getLength = function() {
	var i, sum;
	sum = 0;
	for (i = 0; i < this.length; i++) {
		if ((this.charCodeAt(i) >= 0) && (this.charCodeAt(i) <= 255))
			sum = sum + 1;
		else
			sum = sum + 3;
	}
	return sum;
}

/**
 * @description URI参数转码
 * @returns {string} str
 */
String.prototype.encodeURI = function() {
	return encodeURIComponent(this).replaceAll("%C2%A0","%20");
}

/**
 * @description 根据模式mode参数，该参数可省略，默认为0:before，
 *              before模式为在字符串前补充字符char，如果置模式为1:after， 则在字符串后补充char，到length的长度。
 *              Char参数不传默认为0。 (mode参数可用：0或false;1或true或其他参数)
 * @param {number}length 填充到某个长度
 * @param {boolean} mode 填充方式，有1:after 、 0:before 两种方式，默认为before
 * @param {String} fillChar 填充的字符，默认为0
 * @return {String}
 */
String.prototype.fillChar = function(length, mode, fillChar) {
	if (!fillChar)
		fillChar = "0";

	var len = this.length - length;
	if (len > 0)// 比实际想要的长度更大,默认截取前一部分的数据,如果是要在后面填充，截取的时候会将会后面的部分截取掉
		return mode ? this.substr(0, length) : this.substr(len, length)
	else {
		var appendStr = "";
		len = Math.abs(len) / fillChar.length;
		for (; len > 0; len--) {
			appendStr += fillChar;
		}
		return mode ? this + appendStr : appendStr + this;
	}
};

/**
 * @description 用指定值替换字符串中的占位符
 * @param {Array} values 数组，用于替换占位符
 * @param {boolean} encodeURI 是否需要对values做 URI编码处理，不传默认为否，必须在values为数组对象时有效
 * @return {String} 转码后的值
 */
String.prototype.format = function(values, encodeURI) {
	var args, isEncode;
	if (typeof values == "object") {
		args = values;
		isEncode = encodeURI;
	} else
		args = arguments;

	return this.replace(/\{(\d+)\}/g, function(m, i) {
				return isEncode ? args[i].encodeURI() : ("" + args[i]).encode();
			});
}
String.prototype.formatText = function(data) {
	var args = arguments,reg,text;
	if(args.length == 1 && $.isPlainObject(data))
	{
		reg = /\${([\s\S]*?)}/g;
		args = data;
	}
	else
	{
		reg = /\{(\d+)\}/g;
	}
	
	return this.replace(reg, function(m, i) {
				text = args[i];
				return text == null ? '' : text;
			});
}
String.prototype.formatField = function(data,encodeType) {
	return this.formatByMap(data,null,encodeType);
}

//根据规则格式化
String.prototype.formatByMap = function(data,fnMap,encodeType) {
	var field,sign,format,value,result;
	return this.replace(/\${([\s\S]*?)}/g,function(s,m){
			fnMap && (result = fnMap(m,data));
			if(result === false)
				return s;
			
			switch(sign = m.substr(0,1))
			{
				case "#":
					format = 'text';
					break;
				case "&" :
					format = 'url';
					break;
				default :
					format = null;
					break;
			}
			if(format)
				m = m.substring(1);
			else
				format = encodeType;
				
			var value = Ccay.DataHelper.getObj(m,data); 
			if(value != null)
			{
				if(typeof(value) == 'string' && format != 'non')
					return format ? (format == 'url' ? encodeURIComponent(value) : value) : encode(value);		
				else
					return value;
			}
            return "";
          });
}
/**
 * @description 用指定值替换字符串中的占位符，自动处理encode，动态参数
 */
String.prototype.formatValue = function() {
	var args = arguments;
	return this.replace(/\{(\d+)\}/g, function(m, i) {
				return ("" + args[i]).encode();
			});
}
/**
 * @description 用指定值替换字符串中的占位符，URL参数使用，自动处理encodeURI，动态参数
 */
String.prototype.formatURI = function() {
	var args = arguments;
	return this.replace(/\{(\d+)\}/g, function(m, i) {
				if (args[i] === null)
					return "";
				else if (typeof args[i] == "string") {
					return args[i].encodeURI();
				} else {
					return args[i];
				}
			});
}
/**
 * @description 判断字符是否为空
 * @return {Boolean} 是否为空
 */
String.prototype.isEmpty = function() {
	return this.trim().length == 0;
}
/**
 * @description 判断字符是否为空
 * @return {Boolean} 是否为空
 */
String.prototype.trim = function() {
	return this.replace(/(^[\s　]*)|([\s　]*$)/g, "");
}
$.trim = function(str){
	return  str == null ? "" : str.toString().trim();
}
String.prototype.len = function() {
	var value = this.trim();
	if (value.length)
		return value.replace(/[^x00-xff]/g, "**").length;
	return 0;
}

/**
 * @description 扩展replace方法
 * @param {String} oldstr 被替换的字符
 * @param {String}newstr 替换的字符
 * @return {String}
 */
String.prototype.replaceText = function(oldstr, newstr) {
	return this.replace(new RegExp(oldstr, "gm"), newstr);
}

/**
 * @description tring转换成日期
 * @return {Date}
 */
String.prototype.toDate = function(format) {
	var arr;
	if(this.indexOf("T")>0){//服务器端返回时间处理
		arr= Ccay.Core.DateHandle.getStrArray(this.substr(0,19).replace("T"," "),Ccay.Config.Format.sysDateTime,true);
		arr && arr.push(this.split(".").pop().split("+").shift() * 1); 
	}else{
		arr = Ccay.Core.DateHandle.getStrArray(this,format,this.length > 10);
	}
	
	if(arr && arr[0] > 0 && arr[1] > -1 )
		return new Date(arr[0], arr[1], arr[2] || 1,arr[3] || 0, arr[4] || 0,arr[5]||0,arr[6]||0);
		
	return null;
}

String.prototype.validDate = function(format,isDateTime){
	if(Ccay.Config.Regular.serverDate.test(this)){
		return true;
	} 
	var arr = Ccay.Core.DateHandle.getStrArray(this,format,isDateTime);
	return arr ? (isDateTime ? Ccay.Core.DateHandle.checkDateTimeStr(arr) : Ccay.Core.DateHandle.checkDateStr(arr)) : false;
}

Ccay.Core.DateHandle = {
	getStrArray : function(str,format,isDateTime){
		str = str.trim();
		var regular = this.getDateRegular(str,format,isDateTime);
		if(regular)
		{
			if($.type(regular) == "object")
			{
				var matchValue = str.match(regular.reg),
					textReg = (regular.reg + '').replaceText('d','w'),
					matchText = regular.format.match(new RegExp(textReg.substring(1,textReg.length -1)));
					
				if(matchValue && matchText && matchValue.length == matchText.length)
				{
					var arr=[0,0,0,0,0,0];
					for(var i=1,len = matchValue.length;i<len;i++){
						var value = matchValue[i] * 1;
						if(value || value === 0)
						{
							var text = matchText[i];
							this.matchDateArray(arr,value,text);
						}
					}
					return arr;
				}
			}
			else
			{
				if(str.substring(regular.length).length){
					return null;
				}
				var arr=[0,0,1,0,0,0],valuePos=0,TextPos=0,value,text,notNum;
				for(var i=0,len = str.length;i<len;i++){
					var charValue = str.substr(i,1),notNum = isNaN(charValue * 1) || charValue.trim() == '';
					if(notNum || (i == len -1 && valuePos < i && (i++)))
					{
						notNum || i++;
						value = str.substring(valuePos,i) * 1;
						
						if(notNum)
						{
							valuePos = i+1;
							var end = regular.indexOf(charValue,TextPos);
							end < 0 && (end = regular.length);
							text = regular.substring(TextPos, end);
							TextPos = end+1;
						}
						else
						{
							text = regular.substring(TextPos);
						}
						this.matchDateArray(arr,value,text);
					}
				}
				return arr;
			}
		}
		return null;
	},
	matchDateArray:function(arr,value,text){
		if(text)
		{
			switch(text){
				case "yyyy":
					arr[0] = value;
					break;
				case "MM":
					arr[1] = value-1;
					break;
				case "dd":
					arr[2] = value;
					break;
				case "hh":
					arr[3] = value;
					break;
				case "mm":
					arr[4] = value;
					break;
				case "ss":
					arr[5] = value;
					break;
			}
		}
	},
	getDateRegular : function(value,format,isDateTime){
		if(format == null)
		{
			var name = isDateTime ? "sysDateTime":"sysDate",reg = Ccay.Config.Regular[name];
			if(reg.test(value))
				return {reg:reg,format:Ccay.Config.Format[name]};
				
				name = isDateTime ? "datetime":"date",reg = Ccay.Config.Regular[name];
			if(reg.test(value))
				return {reg:reg,format:Ccay.Config.Format[name]};
				
				name = "dateym",reg = Ccay.Config.Regular[name];
			if(reg.test(value))
				return {reg:reg,format:Ccay.Config.Format[name]}; 		
		}
		return format;
	},
	checkDateStr : function(arr){
		var year = arr[0],month = arr[1],day = arr[2],date = new Date(year,month,day);
	    return date ? (date.getFullYear() == year && date.getMonth() == month && date.getDate() == day) : false;
	},
	checkDateTimeStr : function (arr){
		var year = arr[0],month = arr[1],day = arr[2],hour = arr[3],minute =arr[4],second=arr[5], 
			date = new Date(year,month,day,hour,minute,second);

	    return date ? (date.getFullYear() == year && date.getMonth() == month && date.getDate() == day && date.getHours() ==hour && date.getMinutes() == minute && date.getSeconds() == second) : false;
	}
}



/**
 * @description String转换成日期时间
 * @return {date}
 */
String.prototype.toDateTime = function() {
	return this.toDate();
}
String.prototype.replaceAll = function (oldstr, newstr) {
    return this.replace(new RegExp(oldstr, "gm"), newstr);
}
/** *************************** Array扩展 ************************* */

/**
 * @description 根据值移除数组元素
 * @param {String}
 *            value 该值可以是字符串 对象 或其他类型
 */
Array.prototype.remove = function(value) {
	for (var i = 0,len = this.length; i < len; i++) {
		if (value == this[i])
		{
			this.splice(i, 1);
			i--;
		}
	}
}
Array.prototype.contains = function(value) {
	for (var i = 0,len = this.length; i < len; i++) {
		if (this[i]!=="" && value == this[i] )
			return true;
	}
	return false;
}
Array.prototype.appendFormat = function(str, args) {
	this.push($.isPlainObject(args) ? str.formatField(args) : str.formatText(args));
	return this;
}
Array.prototype.clearRepeating = function(){
	var len = this.length,arr = [],item;
	while(len > 1)
	{
		item = this.shift();
		arr.push(item)
		this.remove(item);
		len = this.length
	}
	len > 0 && (arr = arr.concat(this));
	return arr;
}
/** *************************** Date扩展 ************************* */
/**
 * @description
 * @param {String}   format
 */
Date.prototype.format = function(format) {
	// /<summary>格式化日期</summary>
	// /<param name="format">日期格式字串，为空则为系统默认格式</param>
	// / <returns type="Date" />
	var date= this;
	if (!format)
		format = Ccay.Config.Format.date;
	var o = {
		"M+" : this.getMonth() + 1, // month
		"d+" : this.getDate(), // day
		"h+" : this.getHours(), // hour
		"m+" : this.getMinutes(), // minute
		"s+" : this.getSeconds(), // second
		"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
		"S" : this.getMilliseconds()
		// millisecond
	}
	var yearStr=""+ this.getFullYear();
	if (/(y+)/.test(format))
		format = format.replace(RegExp.$1, yearStr.substr(4 - RegExp.$1.length));
	 
	
	var isMMM = format.indexOf('MMM') > -1;
	if(isMMM)
	   delete o["M+"];
	
	for (var k in o)
		if (k && new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1, RegExp.$1.length == 1? o[k]: ("00" + o[k]).substr(("" + o[k]).length));
	
	if(isMMM){
		format = format.replace('MMM', Ccay.Config.Format.months[this.getMonth()])
	}
	return format;
}

Date.prototype.toJSON = function () {
	//return this.getTime() - 8 * 60 * 60 * 1000 - this.getTimezoneOffset() * 60 * 1000;
	 function f(x, y) {
	 	x = "" + x;
	 	return x.fillChar(y ? 3 : 2);
	 }
	 return  this.getFullYear()   	+ '-' +
             f(this.getMonth() + 1) + '-' +
             f(this.getDate())      + 'T' +
             f(this.getHours())   	+ ':' +
             f(this.getMinutes())   + ':' +
             f(this.getSeconds())   + '.' +
             f(this.getMilliseconds(), true) + '+0800'; 
}
/**
 * @description Liujian wx200947 add 根据时区转换时间
 * @param {String}
 *            timezone： 目标转换时区
 * @param {String}
 *            nowTimeZone： 当前时区
 */
Date.prototype.getUTCTime = function(timezone , nowTimeZone){
	//参数没值 就取当前系统设置时区 并进行截取，格式如：+8 , -8 , -4.5 , +4.5
	if(!timezone || isNaN(timezone)){
		timezone = Ccay.Personalized.global.common.timeZone;
		timezone = timezone.substring(3,timezone.length);
	}
	//判断  目标转换时区  是否为number
	if(!isNaN(timezone)){
		//timezone 最大取值 13，最小取值 -12
		timezone = Math.min(Math.max(timezone,-12),13);
		
		//处理当前时区，默认为北京时间
		if(!nowTimeZone || isNaN(nowTimeZone)){
			//如果等于当前设置时区 则进行截取 + 或 - 及后面部分，否则取值 +8
			nowTimeZone = nowTimeZone == Ccay.Personalized.global.common.timeZone ? nowTimeZone.substring(3,nowTimeZone.length) : nowTimeZone = "+8";;
		}else{
			//设置最大取值 13 最小值-12
			nowTimeZone = Math.min(Math.max(nowTimeZone,-12),13);
		}
		
		if(timezone === nowTimeZone){
			return this;
		}
		
		var utcTime = this.getTime() - ( nowTimeZone * 3600000 );
		return new Date(utcTime + timezone*3600000);
	}
	return this;
}

Date.prototype.toString = function(){
	return this.toJSON();
},
Date.prototype.addMonth = function(m){
	
	var date=new Date(this.getTime());
	//判断是否是月底
	var isEndDay =  date.getDate() == date.getMonthDay();
	//如果是月底，则加上一天
	var newM = date.getMonth() + m;
	date.setMonth( newM );
	
	if(date.getMonth() != (newM + 12) % 12){
		date.setDate(0);
	}
	//如果之前是月底，则将新生成的日期，也设置成月底
	if(isEndDay){
		date.setDate(date.getMonthDay());
	}
	return date;
}

/**
 * 得到当前月份有多少天
 * @type 
 */
Date.prototype.getMonthDay = function(){
	var dateArr=[[31,28,31,30,31,30,31,31,30,31,30,31],[31,29,31,30,31,30,31,31,30,31,30,31]];
	var currYear=this.getFullYear();
	if(currYear % 4 == 0 &&  currYear % 100 > 0 || currYear % 400 == 0 ){
		return dateArr[1][this.getMonth()];
	}else{
		return dateArr[0][this.getMonth()];
	}
}
Date.prototype.toDate = function () {
	return this;
}
Date.prototype.toDateTime = function () {
	return this;
}
/** *************************** function ************************* */
Function.prototype._injectBefore = function(fn){
	var self = this;
	return function(){
		if(fn.apply(this,arguments) !== false)
			self.apply(this,arguments);
	};
}
Function.prototype._injectAfter = function(fn){
	var self = this;
	return function(){
		if(self.apply(this,arguments) !== false)
			fn.apply(this,arguments);
	};
}
/** *************************** Format ************************* */

Ccay.Format = {
	toDate : function(value,format){
		if(value){
			var date,type = typeof(value) ;
			if(type== "number" || !isNaN(value))
			{
				date = new Date(value*1);
			}
			else if(type== "object"){
				date = value;
			}
			else if(type== "string")
			{
				date = value.toDate(format);
			}
			return date;
		}
		return value;
	},
	toDateTime : function(value, format){
		return this.toDate(value, format || Ccay.Config.Format.datetime);
	},
	toDateStr : function(value,format,renderFormat){
		return value ? this.toDate(value, format || Ccay.Config.Format.date).format(renderFormat || format || Ccay.Config.Format.date) : value; 
	},
	toDateTimeStr : function(value,format,renderFormat){
		return value ? this.toDateTime(value, format).format(renderFormat || format || Ccay.Config.Format.datetime) : value;
	},
	toUTCDateTimeStr : function(data,value){
		if(data._updated === true || data._inserted === true || !value){
			return Ccay.Format.toDateTimeStr(value);
		}
		return Ccay.Format.toDateTimeStr(value.getUTCTime(Ccay.Personalized.global.common.timeZone,8));
	},
	
	toDateYM : function(value,format,renderFormat){
		return value ? this.toDate(value, format).format(renderFormat || format || Ccay.Config.Format.dateym) : value;
	},
	toDateYMStr : function(value,format,renderFormat){
		return value ? this.toDateYM(value, format).format(renderFormat || format || Ccay.Config.Format.dateym) : value;
	},
	toInt : function(value,fraction){
		return value != null ? parseInt(value) : value;
	},
	toDecimal : function(value,fraction){
		if(typeof value == "number"){
	        if (fraction == void 0)
	            fraction = Ccay.Config.Format.decimalfraction;
			 return parseFloat(value).toFixed(fraction);
		/*}else if(typeof value == "string" && !isNaN(value)){
			 return this.toDecimal(Ccay.Format.toNumber(value),fraction);
		}*/
		}else if(typeof value == "string" && value !== "" && !isNaN(value)){
			 return this.toDecimal(Ccay.Format.toNumber(value),fraction);
		}
		return value;
	},
	toCurrency : function(value,fraction,flag){
		if(!Ccay.DataHelper.isEmpty(value)){
			value = this.toDecimal(value,fraction);
			value = value.replace(/(^|[^\w.])(\d{4,})/g, function ($0, $1, $2) {
	            return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
	        });
	        if(!flag)
	        	flag = Ccay.Config.Format.currencyFlag;
	        
			return flag ? flag.replace('[currency]',value).formatText(value) : value;
		}else{
			return "";
		}
	},
	toCurrencyStr : function(value,fraction,flag){
		if(!Ccay.DataHelper.isEmpty(value)){
			if (fraction == void 0)
	            fraction = Ccay.Config.Format.decimalfraction;
			
			
			var idx = value.indexOf(".");
			if(-1 == idx){
				if(value.length > 15){
					value +=".";
					for (var i = 0; i < fraction; i++) {
						value +="0"
					}
				}else{
					value = this.toDecimal(value,fraction);
				}
			}else{
				if(idx > 15){
					var tmp = value.substring(idx-1);
					var fractionValue =  parseFloat(tmp).toFixed(fraction);
					value = value.substring(0,idx)+fractionValue.substring(1);
				}else{
					value = this.toDecimal(value,fraction);
				}
			}
			value = value.replace(/(^|[^\w.])(\d{4,})/g, function ($0, $1, $2) {
	            return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
	        });
	        if(!flag)
	        	flag = Ccay.Config.Format.currencyFlag;
	        
			return flag ? flag.replace('[currencystr]',value).formatText(value) : value;
		}else{
			return "";
		}
	},
	/** 文件大小值 单位互相转换
	 * @param {number} value    文件大小数值
	 * @param {string} unit     转换后单位
	 * @param {string} currUnit  当前单位，不传默认为B     值可为B K M G T
	 * @return {String}
	 */
	toFileSize : function(value,unit, currUnit){
		if(value === 0){
			return "0" + (currUnit ||　unit ||　"B");
		}
		for(var i = 0, length = Ccay.Config.Format.fileSize.length; currUnit && i < length; i++){
			if(currUnit == Ccay.Config.Format.fileSize[i]){
				break;
			}
			value *= 1024;
		}

		if(value){
			var level = 0,end = false;
			while(!end){
				value = value / 1024;
				level++;
				
				if(unit){
					if(unit == Ccay.Config.Format.fileSize[level] || value < 0.1)
						end = true;
				}
				else
					end = !(value > 1024);
			}
			return this.toDecimal(value,Ccay.Config.Format.fileSizeFraction) 
				+ ' ' + Ccay.Config.Format.fileSize[level];
		}
		return '';
	},
	toNumber:function(value){
		if(value && typeof(value) == "string")
		{
			// 判断是否是负数的情况
			if (isNaN(value * 1) && isNaN(value[0]) && (value[0] != "-")) {
				value = value.substring(1);
			}
			return value.replaceText(',','') * 1;
		}
		return value;
	},
	toEllipsis: function(value, len) {
		if (value)
		{
			var text, css;
			if(typeof(len) == "number" && len < value.length)
				text = value.substr(0, len) + "...";
			else
				text = value;
		}
		return "<label class='ccay-Text-Ellipsis' title=\"{1}\">{0}</label>".formatValue(Ccay.Format.formatSpace(text) || value || "", value || "");
	},
	toBoolView: function (value, htmlView, noFork) {
		if (value == null) {
			return "";
		}
		var text = (value != 0 || value != false) ? Ccay.Config.Format.yes : Ccay.Config.Format.no;
		if (htmlView) {
			if (noFork == true) {
				return (value != 0 || value != false) ? ("<a class='ccay-icon yes nocursor' title='" + text + "' ></a>") : ""
			} else {
				return "<a class='ccay-icon {0} nocursor' title='{1}' ></a>".format((value != 0 || value != false) ? 'yes' : 'no', text);
			}
		}
		return text;
	},
	toDateNum:function(date){
		return Date.parse(date);
	},
	toRate:function(value,total,fraction,htmlView,section){
		if(value)
			value = this.toDecimal(value * 100 / (total || 1),fraction || 0);
		else
			value = 0;
		
		var css;
		if(section){
			if(value == 100)
				css = "completed";
			else{
				var sCss = {0:'danger',1:'warning',2:'normal'}
				$.isArray(section) || (section = section.split(','));
				$.each(section,function(i,n){
					if(value < n)
					{
						css = sCss[i];
						return false;
					}
				});
			}	
		}
		value += "%";
		if(htmlView)
			return "<div class='ccay-data-rate'><div class='rate-chart " + (css || "") + "' style='width:"
				+ value + "'/><span class='rate-text'>" + value + "</span></div>";

		return value;
	},
	toDateBefore:function(date){
		if(!date){
			return "";
		}
		if(typeof(date) == 'number'){
			date = Ccay.Format.toDate(date);
		}else if(typeof(date)=="string"){
			date=date.toDate();
		}
		
		var now = Ccay.Core.getServerTime(),
			year = now.getFullYear() - date.getFullYear(),
			month = now.getMonth() - date.getMonth();
			
		if(date > now){
			//未来时间，不处理
			return date.format(Ccay.Config.Format.datehm);
		}

		if(year){
			//年份不相等，直接输出
			return date.format(Ccay.Config.Format.datehm);
		}
		
		if(checkDayNum(year,month))
		{
			year--;
			month += 12;
		}
		var day = now.getDate() - date.getDate(),
			hour = now.getHours() - date.getHours(),
			minute = now.getMinutes() - date.getMinutes();
			
		if(checkDayNum(month,day))
		{
			month--;
			day += new Date(now.getFullYear(),now.getMonth(),0).getDate();
		}
//		if(checkDayNum(day,hour))
//		{
//			day--;
//			hour +=24;
//		}
//		if(checkDayNum(hour,minute))
//		{
//			hour--;
//			minute+=60;
//		}
		if(month > 0 || (month == 0 & day > 2))
			return date.format($i18n('ccay.common.format.dateMD'));
		
		if(day > 0 || (day ==0 && hour > 0)){
			var textDay = $i18n('ccay.common.format.day').split(',')[day];
			return textDay + date.format(' hh:mm');
		}
		
		if(minute > 0)
			return $i18n('ccay.common.format.minuteBefore').formatText(minute);
		
		return $i18n('ccay.common.format.Just');
		
		function checkDayNum(num1,num2){
			if(num1 > 0){
				if(num2 < 0)
					return true;
			}
			return false;
		}
	},
	toValueObj:function(value, data, valueField, displayField){
		if(value !== null)
		{
			if(!$.isPlainObject(value))
			{
				value = {value:value};
			}
			if(value.value && value.text == null && data)
			{
				value.text = this.getArrayText(value.value,data, valueField, displayField);
			} 
			return value;
		}
		return {};
	},
	getPixe:function(size){
		if(typeof(size) == "number")
			return size + 'px';
		return size;
	},
	/************************* 数据集合处理 ********************/
	getField:function(field,name){
		return field || Ccay.Config.Format[name + 'Field'];
	},
	getArrayItem: function(value, datas, valueField){
    	if(datas){
    		valueField = this.getField(valueField,'value');
    		for(var i=0,len =datas.length; i<len; i++){
    			if(datas[i][valueField] == value)
    				return datas[i];
    		}
    	}
    	return null;
	},
	getArrayText: function(value, datas, valueField, displayField){
    	var valueObj = this.getArrayItem(value, datas, valueField);
    	return valueObj ? valueObj[this.getField(displayField,'display')] : "";
	},
	//复杂数组转换成对象
	convertArrayToObject : function(dataArray, valueField, displayField){
		if(dataArray && dataArray.length){
			var obj = {};
			valueField = this.getField(valueField,'value');

			displayField = displayField === true ? null : this.getField(displayField,'display');
				
			for(var i=0,item=dataArray[0]; item; i++,item = dataArray[i]){
				obj[item[valueField]] = displayField ? item[displayField] : item;
			}
			return obj;
		}
		return dataArray;
	},
	//简单数组转换成对象
	convertSimpleArrayToObject: function (dataArray, valueField, displayField) {
		if(dataArray && dataArray.length){
			var obj = {};
			valueField = this.getField(valueField,'value');
			displayField = this.getField(displayField,'display');
			if (!$.isPlainObject(dataArray[0])) {
				for(var i=0,item=dataArray[0]; item; i++,item = dataArray[i]){
					var childObj = {};
					childObj[valueField] = childObj[displayField] = item;
					obj[i] = childObj;
				}
				return obj;
			} else {
				return dataArray;
			}
		}
		return dataArray;
	},
	getObjectText: function (value, obj) {
		if (value != null) {
			if (typeof(obj) == "string")
				obj = Ccay.Cache.get(obj);
			
			if (obj) {
				var valueSplit = Ccay.Config.Format.valueSplit;
				var value = value.toString();
				if (value.indexOf(valueSplit) > 0) {
					var arrText = [],values = value.split(",");
					for (var i=0,v = values[0]; v; i++,v = values[i]) {
						arrText.push(obj[v] || v);
					}
					return (arrText.join(Ccay.Config.Format.textSplit)+"").encode();
				}
				else
					return ((obj[value] || value)+"").encode();
			}
		}
		return null;
	},
	showPersonInfo: function (valueField, displayField, data) {
		var value = Ccay.DataHelper.getObj(valueField, data),
			text = Ccay.DataHelper.getObj(displayField, data);
		return (value && text) ? "<a href='javascript:Ccay.Component.popUserInfo(\"{0}\")'>{1}</a>".formatValue(value, text) : "";
	},
	showGroupInfo: function (valueField, displayField, data) {
		var value = Ccay.DataHelper.getObj(valueField, data),
			text = Ccay.DataHelper.getObj(displayField, data);
		return (value && text) ? "<a href='javascript:Ccay.Component.popGroupInfo(\"{0}\")'>{1}</a>".formatValue(value, text) : "";
	},
	formatSpace: function (value) {
		if (typeof value == "string") {
			return value.replace(/&/g,"&#38;")
				.replace(/</g,"&lt;")
				.replace(/>/g, '&gt;')
				.replace(/"/g, '\"')
				.replace(/\s/g, "&nbsp;");
		} 
		return value;
	},
	formatAmount: function(field,amountField,codeField,decimalLen,data){
		var amount = Ccay.DataHelper.getObj(amountField, Ccay.DataHelper.getObj(field,data)||{});
		if(amount){
			amount = Ccay.Format.toCurrency(Ccay.Format.toNumber(amount),decimalLen);
			var code = Ccay.DataHelper.getObj(codeField, Ccay.DataHelper.getObj(field,data)||{});
			if(code){
				return code + amount;
			}
			return "CNY" + amount;
		}
		return null;
	},
	dateFormatStrByLang:function(format){
		var formatter = Ccay.Config.dataFormatter[workspaceVO.currentLanguage];
		return format ? (formatter[format] || formatter["datetime"]) : formatter["datetime"];
	},
	boolRender:function(gridId,value,bool){
		if(bool){
			return "";
		}
		return '<input type="checkbox" onclick="Ccay.Format.boolClickCheck(\''+gridId+'\',this)" '+(value?'checked="checked"':'')+'/>'
	},
	boolClickCheck:function(gridId,chk){
		var grid = $("#"+gridId).manager(),
			cell=$(chk).parent(),
			col=grid.getColumnOp(cell);
		var value = Ccay.Format.boolParse(chk.checked,col.format);
		var updateBool = grid.cellValue(cell,col,value,true);
		updateBool === false && (chk.checked = false);
		updateBool && !cell.hasClass("cell-update") && cell.addClass("cell-update");
	},
	boolParse : function(value, format) {
		if(format && format.nullValue)
		{
			if(value == null || value == '')
				return null;
		}
		var type = typeof(value);
		if (type != 'boolean') {
			if(value == "true" || value == '1')
				value = true;
			else
				value = false;
		}
		// 判断格式化值
		if (format && format.isBool) {
			return value ? true : false;
		} else {
			return value ? 1 : 0;
		}
	},
	getLangugaeList : function(){
		var languageList = [{
			id : "zh_CN",
			text : $i18n("ccay.common.label.lang.chinese")
		}, {
			id : "en_US",
			text : $i18n("ccay.common.label.lang.english")
		}];
		Array.prototype.push.apply(languageList,workspaceVO.languageList);
		$.each(workspaceVO.languageList,function(i,d){
			d.text = $i18n(d.text);
		});
		return languageList;
	}
}



/*** ----------------------------- Begin Ccay扩展对象* --------------------------------*/

/**
 * @description js 扩展对象，其功能属性模拟与java中的HashMap
 */
Ccay.HashMap = function() {
	/** 存放键的数组(遍历用到) */
	this.keys = new Array();
	/** 存放数据 */
	this.data = new Object();
	/**
	 * @description 放入一个键值对
	 * @param {String}
	 *            key
	 * @param {Object}
	 *            value
	 */
	this.put = function(key, value) {
		if (this.data[key] == null) {
			this.keys.push(key);
		}
		this.data[key] = value;
	};
	/**
	 * @description 获取某键对应的值
	 * @param {String}
	 *            key
	 * @return {Object} value
	 */
	this.get = function(key) {
		return this.data[key];
	};
	/**
	 * @description 删除一个键值对
	 * @param {String}
	 *            key
	 */
	this.remove = function(key) {
		this.keys.remove(key);
		this.data[key] = null;
	};
	/**
	 * @description 遍历Map,执行处理函数
	 * @param {Function}
	 *            回调函数 function(key,value,index){..}
	 */
	this.each = function(fn) {
		if (typeof fn != 'function') {
			return;
		}
		var len = this.keys.length;
		for (var i = 0; i < len; i++) {
			var k = this.keys[i];
			fn(k, this.data[k], i);
		}
	};

	/**
	 * @description 获取键值数组(类似Java的entrySet())
	 * @return 键值对象{key,value}的数组
	 */
	this.entrys = function() {
		var len = this.keys.length;
		var entrys = new Array(len);
		for (var i = 0; i < len; i++) {
			entrys[i] = {
				key : this.keys[i],
				value : this.data[ this.keys[i] ]
			};
		}
		return entrys;
	};

	/**
	 * @description 判断Map是否为空
	 */
	this.isEmpty = function() {
		return this.keys.length == 0;
	};

	/**
	 * @description 获取键值对数量
	 */
	this.size = function() {
		return this.keys.length;
	};

	/**
	 * @description 重写toString
	 */
	this.toString = function() {
		var s = "{";
		for (var i = 0; i < this.keys.length; i++, s += ',') {
			var k = this.keys[i];
			s += k + "=" + this.data[k];
		}
		s += "}";
		return s;
	};
};

/**
 * Ccay.StringBuilder 字符处理对象构建方法
 * 
 * @constructor {StringBuilder}
 * @param {String}
 *            value 初始值
 */
Ccay.StringBuilder = function(value) {

	this.strings = new Array();
	if (value && value.length > 0)
		this.append(value);
}

/**
 * 拼接的字符串
 * 
 * @param {String}
 *            value 需要拼接的字符串
 * @return {StringBuilder} 对象本身
 */
Ccay.StringBuilder.prototype.append = function(value) {
	if (value && value.length > 0)
		this.strings.push(value);
	return this;
}

/**
 * 是否为空
 * 
 * @return {boolean}
 */
Ccay.StringBuilder.prototype.isNotEmpty = function() {
	return this.strings.length > 0;
}
/**
 * @description 清空内容
 */
Ccay.StringBuilder.prototype.clear = function() {

	this.strings.length = 0;
}

/**
 * 转换为字符串返回
 * 
 * @param {String}
 *            split 分割字符
 * @return {String}
 */
Ccay.StringBuilder.prototype.toString = function(split) {
	return this.strings.join(split || "");
}

/**
 * 删除最后一个添加的对象
 * 
 * @return {StringBuilder}
 */
Ccay.StringBuilder.prototype.removeLast = function() {
	this.strings = this.strings.slice(0, -1);
	return this;
}

/** ----------------------------- End Ccay扩展对象 -------------------------------- */

	   var Const = {
			/**
			 * 需要转义的特殊字符
			 */
			escape : {
				"&" : "&amp;",
				"<" : "&lt;",
				">" : "&gt;",
				'"' : "&quot;",
				"'" : "&#x27;",
				"`" : "&#x60;"
			},
			badChars : /[&<>"'`]/g,
			possible : /[&<>"'`]/
		}
		/** Ccay.DataHelper 数据处理类 */
		Ccay.DataHelper = {
			escape : function(string) {// 变量表达式转义
				if (string == null /* || string === false */) {
					return string;
				}
				string = string.toString();
				if (!Const.possible.test(string)) {
					return string;
				}
				return string.replace(Const.badChars, function(chr) {
					return Const.escape[chr] || "&amp;";
				});
			},
			compare:function(value1,value2,ignoreEmpty){
				if(ignoreEmpty)
				{
					if((value1 == null && value2 === "") || (value1 === "" && value2 == null))
						return false;
				}
				return value1 != value2;
			},
			hasValue : function(value) {
				return typeof value != "undefined" && value != null;
			},
			/**
			 * 返回参数中第一个不为空的值，如果都为空，则返回空字符串
			 * 
			 * @param 可接受多个参数，
			 * @return {String}
			 */
			getValue : function() {
				for (var i = 0; i < arguments.length; i++) {
					if (Ccay.DataHelper.hasValue(arguments[i]))
						return arguments[i];
				}
				return "";
			},
			/**
			 * @description 判断字符串是否为空的方法 根据情况判断一下集中模式 undefined 、"undefined" 、null、"null" 、空字符串
			 * @param str需要判断的字符串
			 */
			isEmpty : function(str) {
				if (Ccay.DataHelper.hasValue(str)) {
					str += '';
					return str && str.trim().length > 0 ? false : true;
				}

				else
					return true;
			},
			/**
			 * @description 转换成浮点数
			 * @param value {number}
			 * @param fraction {}
			 */
			toDecimal : function(value, fraction) {
				if (value)
					return parseFloat(value).toFixed(fraction
							|| Ccay.Config.Format.decimalfraction);

				return value;
			}
			/**
			 * @description 将Json对象转化成String对象
			 * @param json {Json}
			 * @return {String}
			 */
			,
			toJsonStr : function(json) {
				return json ? JSON.stringify(json) : "";
			}
			/**
			 * @description  将op中配置转换成可输出的html
			 * @param op	属性对象
			 * @param opArr 要组合的属性key集合
			 * @return {String}
			 */
			,
			buildJmlConfStr : function(op,opArr){
				if(opArr == null || opArr.length == 0){
					return "";
				}
				var tem = new Array();
				for(var i=0;i<opArr.length;i++){
					if(op[opArr[i]] != null){
						tem.push(opArr[i] +" = '" + op[opArr[i]] + "' ");
					}
				}
				return tem.join("");
			}
			/**
			 * @description 将String对象转化成Json对象
			 * @param str {String}
			 * @return {Json}
			 */
			,
			toJson : function(str) {
				return Ccay.DataHelper.isEmpty(str) ? null : JSON.parse(str);
			},
			/**
			 * @description 判断是否在范围内
			 * @param value {number} 需要比较的值
			 * @param min {number} 最小值
			 * @param max {number} 最大值
			 * @return {number}
			 */
			inRange:function(value,min,max){
				return value >= min && value <= max;
			},
			/**
			 * @description 比较value，获取范围内数据
			 * @param value {number} 需要比较的值
			 * @param min {number} 最小值
			 * @param max {number} 最大值
			 * @return {number}
			 */
			getRangeValue : function(value, min, max) {
				if (value < min)
					value = min;
				else if (value > max)
					value = max;
				return value;
			},
			getObj:function(names, data,formRoot){
				if(names){
				names = names.split('.');
				var obj = data || window,len = names.length;
				if(len > 1)
				{
					for (var i = formRoot ? 1 : 0; i < len; i++) {
						obj = obj[names[i]];
						if(obj == null)
							return null;
					}
					return obj;
				}
				else
					return obj[names[0]];
				}
			},
			setObj:function(names, data, value)
			{
				if(names){
				names = names.split('.');
				var obj = data || window,name,len = names.length,target,tmpl;
				if(len > 1)
				{
					len--;
					tmpl = obj;
					for (var i = 0; i < len; i++) {
						name = names[i];
						target = tmpl[name];
						if(target == null)
							target = tmpl[name] = {};
							
						tmpl = target;
					}
					tmpl[names[len]] = value;
				}
				else
					obj[names[0]] = value;
					
				return obj;
				}
			},
			getDataChange:function(newData,oldData,keys){
				var data = {},helper = this,changeNum = 0;
				$.each(newData,function(name,value){
					var oldValue = oldData[name],isChange;
					if($.isPlainObject(value))
					{
						value = helper.getDataChange(value,oldValue,keys);
						isChange = value != null;
					}
					else if($.type(value) == 'array')
					{
						var key = keys[name],arr = new Array(value.length);
						if(key)
						{
							value = helper.getObjectArrayChange(value,oldValue,arr,key,keys);
						}
						else
						{
							value = helper.getArrayChange(value,oldValue,arr);
							//value != oldValue && (data[name] = value);
						}
						isChange = value != null;
					}
					else {
						if(value || oldValue)
							isChange = value != oldValue;
						else if(value !== "" && oldValue != null)
							isChange = value != oldValue;	
					}
					
					if(isChange)
					{
						changeNum++;
						data[name] = value
					}
				});
				return changeNum ? data : null;
			},
			getArrayChange:function(newArr,oldArr,arr){
				var changeNum = 0;
				$.each(newArr,function(i,value){
					var oldValue = oldArr[i];
					if(value != oldValue)
					{
						changeNum++;
						arr[i] = value;
					}
				});
				return changeNum ? arr : null;
			},
			getObjectArrayChange:function(newArr,oldArr,arr,key,keys){
				var changeNum = 0;
				$.each(newArr,function(i,newData){
					var oldData = oldArr[i],data = {};
					$.each(newData,function(name,value){
						if(key != name)
						{
							var oldValue = oldData[name];
							value != oldValue && (data[name] = value);
						}
					})
					if(!$.isEmptyObject(data))
					{
						data[key] = oldData[key];
						arr[i] = data;
						changeNum++;
					}
				});
				return changeNum ? arr : null;
			},
			applyChangeData: function (data, changeData, keys, fnChange){
				var helper = this;
				$.each(changeData,function(name,changeValue){
					var oldValue = data[name],type = $.type(changeValue);
					if(oldValue && type == $.type(oldValue))
					{
						if($.isPlainObject(changeValue))
						{
							if($.isPlainObject(oldValue) && !$.isEmptyObject(oldValue))
							{
								helper.applyChangeData(oldValue, changeValue, keys, fnChange);
								return;
							}			
						}
						else if(type == 'array')
						{
							if(oldValue.length)
							{
								var key = keys && keys[name];
								if(key)
								{
									helper.applyArrayChange(oldValue, changeValue, key, keys, fnChange);
									return;
								}
								
							}
						}
					}
					if (!fnChange || fnChange(name, changeValue, oldValue) !== false) {
						data[name] = changeValue;
					}
				})
			},
			// 应用数组中变化的值
			applyArrayChange:function(arr, changeArr, key, keys, fnChange){
				$.each(changeArr,function(i, changeData){
					if(changeData)
					{
						var keyData = changeData[key], isHas;
						if (keyData) {
							$.each(arr,function(j, data){
								if(data && data[key] == keyData)
								{
									if (!fnChange || fnChange(key, changeData, i, data, j) !== false) {
										$.extend(true, data, changeData);
									}
									isHas = true;
									return false;
								}
							});
							// 如果原始数组中不存在新数组中的数据时，将新数据添加的原始数组中
							if (!isHas && (!fnChange || fnChange(key, changeData, i) !== false)) {
								arr.push(changeData);
							}
						}
					}
				});
			},
			copyField:function(data,fields){
				if(fields){
					var copy = {};
					$.each(fields,function(i,field){
						copy[field] = data[field];
					});
					return copy;
				}
				else
					return $.extend({},data);
			},
			copyArray: function (arr) {
				var helper = this,
					copyArr = [];
				$.each(arr, function (i, data) {
					copyArr.push(helper.copyField(data));
				});
				return copyArr;
			},
			parseUrlParams : function(url){
				var index = url.indexOf('?') + 1,params,args,item,value;
				if(index > 0 && index < url.length)
				{
					params = url.substring(index).split('&');
					if(params.length){
						args = {};
						$.each(params,function(i,param){
							item = param.split('=');
							if(value = item[1])
							{
								Ccay.DataHelper.setObj(item[0],args,decodeURIComponent(value));
							}
						})
					}
				}
				return args;
			},
			languageExtraction:function(value) {
				if(value == null){
					return "";
				};
				var language = workspaceVO.currentLanguage;
				//设置格式，用于判断是否是有效的语种
				language = ","+language+"=";
				var newValue = ","+value;
				var localIndex = newValue.indexOf(language);
				var validLanguages = workspaceVO.validLanguages;
				var nextIndex = -1,tempIndex = -1;
				for (var i = 0; i < validLanguages.length; i++) {
					var validLanguage = ","+validLanguages[i]+"=";
					tempIndex = newValue.indexOf(validLanguage);
					//当value中不存在当前语，并存在其它语种时，返回回“”;
					if(tempIndex !=-1 && localIndex == -1){
						return "";
					}
					if(tempIndex>localIndex){
						newValue = newValue.substring(0,tempIndex);
						nextIndex = tempIndex;
					}
				};
				if(localIndex == -1 && nextIndex == -1){
					return value;
				}
				localIndex = language.length+localIndex;
				return nextIndex == -1? newValue.substring(localIndex):newValue.substring(localIndex,nextIndex);
			}
	};
})()

